package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Override
    public void insert(String keyword, Integer userId) {
        /**
         * 这里因为是异步调用，重新开了一个线程，所有用不了threadlocal,而是传递userId
         */
        //1.查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.存在 更新创建时间
        if (apUserSearch != null){
            apUserSearch.setCreatedTime(new Date());
            //保存
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3.查出的关键词不存在，判断当前历史记录总数量是否超过10
        //保存这个新的
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        //构建查询条件和排序条件
        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC));

        //查询
        List<ApUserSearch> userSearchList = mongoTemplate.find(query1, ApUserSearch.class);

        if (userSearchList == null || userSearchList.size() < 10){
            //总数据量没有超过10，就保存
            mongoTemplate.save(apUserSearch);
        }else {
            //总数据量超过了10
            //获取该集合的最后一个数据
            ApUserSearch  lastUserSearch = userSearchList.get(userSearchList.size() - 1);

            //使用新数据代替该数据
            Query query2 = Query.query(Criteria.where("id").is(lastUserSearch.getId()));
            //第一个参数是Query类型
            mongoTemplate.findAndReplace(query2,apUserSearch);
        }
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {

        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createTime")), ApUserSearch.class);

        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 删除搜索历史
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {

        //1.检查参数
        if(historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.删除
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("id").is(historySearchDto.getId())),ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
